import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_page/game_detail_page_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_round.dart';
import 'package:flutter_09_game/pages/game/game_detail/widgets/widget_round_ball.dart';
import 'package:flutter_09_game/pages/game/game_detail/widgets/countdown_progress_painter.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/btn_dropdown.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class WidgetBetResult extends StatelessWidget {
  const WidgetBetResult(
      {super.key,
      required this.gameLogic,
      // required this.logic,
      this.isPage = true});

  // Rx<ModelGameRound> gameRoundRx ;
  final bool isPage;

  final GameDetailLogic gameLogic;

  // final GameDetailPageLogic logic;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      ModelGameRoundHistory? history =
          gameLogic.gameRoundRx.value.history?.firstOrNull;
      if (history == null) {
        return const SizedBox();
      } else {
        return _buildBetView(history);
      }
    });
  }

  Widget _buildBetView(ModelGameRoundHistory history) {
    return Container(
      margin: EdgeInsets.all(12.w).copyWith(top: 0),
      decoration: BoxDecoration(
        color: AppColor.color121417, // 深色背景
        borderRadius: BorderRadius.circular(8.w),
      ),
      padding: EdgeInsets.all(8.w),
      child: Column(
        children: [
          // 顶部区域：三个信息区域
          Row(
            children: [
              // 左侧区域：开奖信息
              Expanded(child: _buildLeftInfoSection(history)),
              // 8.horizontalSpace,
              // 中间区域：倒计时
              _buildCenterCountdownSection(),
              // 8.horizontalSpace,
              // 右侧区域：下一期信息
              Expanded(child: _buildRightInfoSection(history)),
            ],
          ),
          4.verticalSpaceFromWidth,
          // 底部区域：开奖结果
          _buildResultSection(history),
          6.verticalSpaceFromWidth,
        ],
      ),
    );
  }

  /// 构建左侧信息区域
  Widget _buildLeftInfoSection(ModelGameRoundHistory history) {
    return Column(
      children: [
        // 开奖号码和验证标签
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              (history.round ?? '').toString(),
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: AppColor.textPrimary.withOpacity(0.94),
              ),
            ),
            4.horizontalSpace,
            GestureDetector(
              onTap: () {
                UtilsOther.openVerify(history.round);
              },
              child: Text(
                LocaleKeys.verify.tr,
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w400,
                  color: AppColor.primary,
                ),
              ),
            ),
          ],
        ),
        4.verticalSpaceFromWidth,
        // 期数信息
        Text(
          '${history.issue ?? ''}期',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.textPrimary.withOpacity(0.5),
          ),
        ),
        4.verticalSpaceFromWidth,
        // 状态信息和结果图标
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              LocaleKeys.lotteryOpenedBlock.tr,
              style: TextStyle(
                fontSize: 12.sp,
                fontWeight: FontWeight.w400,
                color: AppColor.textPrimary.withOpacity(0.7),
              ),
            ),
            4.horizontalSpace,
            // 结果图标
            WidgetRoundBall(result: history.result),
          ],
        ),
      ],
    );
  }

  /// 构建中间倒计时区域
  Widget _buildCenterCountdownSection() {
    return SizedBox(
      width: 50.w,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 外层圆形背景
          Container(
            width: 50.w,
            height: 50.w,
            decoration: const BoxDecoration(
              color: AppColor.color212227,
              shape: BoxShape.circle,
            ),
          ),
          // 进度条圆形 - 从顶部开始顺时针绘制
          if (gameLogic.rotationAnimation != null)
            AnimatedBuilder(
              animation: gameLogic.rotationAnimation!,
              builder: (context, child) {
                return CustomPaint(
                  size: Size(50.w, 50.w),
                  painter: CountdownProgressPainter(
                    progress: gameLogic.rotationAnimation!.value,
                  ),
                );
              },
            ),

          // 内层圆形背景
          Container(
            width: 36.w,
            height: 36.w,
            decoration: BoxDecoration(
              color: AppColor.color22242A,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: AppColor.primary.withOpacity(0.6),
                  blurRadius: 6.w,
                  offset: Offset(0, 3.w),
                ),
              ],
            ),
          ),
          // 倒计时数字 - 显示实际倒计时
          Obx(() => Text(
                gameLogic.countdown.value.toString(), // 只显示秒数
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w900,
                  color: AppColor.primary,
                ),
              )),
        ],
      ),
    );
  }

  /// 构建右侧信息区域
  Widget _buildRightInfoSection(ModelGameRoundHistory leftHistory) {
    // ModelGameRoundHistory.fromJson(leftHistory.toJson());
    ModelGameRoundHistory? history = gameLogic.rightHistoryRx.value;
    if (history == null) {
      return const SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        // 下一期号码
        Text(
          (history.round ?? 0).toString(),
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            color: AppColor.textPrimary.withOpacity(0.94),
          ),
        ),
        4.verticalSpaceFromWidth,
        // 下一期期数
        Text(
          '${((history.issue ?? 0))}期',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.textPrimary.withOpacity(0.5),
          ),
        ),
        4.verticalSpaceFromWidth,
        // 下一期标签
        SizedBox(
          height: 20.w,
          child: Text(
            LocaleKeys.lotteryNextIssue.tr,
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: AppColor.textPrimary.withOpacity(0.7),
            ),
          ),
        )
      ],
    );
  }

  /// 构建结果区域
  Widget _buildResultSection(
    ModelGameRoundHistory history,
  ) {
    // String hash = UtilsOther.getLastSixDigits(history.blockHash,count: 8);
    // // 以字符串里面最后一个作为分解点
    // String resultStr = history.result.toString();
    // int lastIndex = hash.lastIndexOf(resultStr);
    // List<String> hashs;
    // if (lastIndex != -1) {
    //   hashs = [
    //     hash.substring(0, lastIndex),
    //     hash.substring(lastIndex, lastIndex + resultStr.length),
    //     hash.substring(lastIndex + resultStr.length),
    //   ];
    // } else {
    //   hashs = [hash, ''];
    // }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          '${LocaleKeys.drawResult.tr}：',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.textPrimary.withOpacity(0.7),
          ),
        ),
        4.horizontalSpace,
        UtilsOther.buildHashDigitsViewString(
            history.blockHash ?? '', history.result),
        Text(
          '(${_getResultText(history.result)})',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w500,
            color: UtilsOther.getResultColor(history.result),
          ),
        ),
      ],
    );
  }

  // /// 获取区块哈希的最后6位
  // String _getLastSixDigits(String? blockHash) {
  //   if (blockHash == null || blockHash.isEmpty) {
  //     return '...000000';
  //   }
  //   if (blockHash.length >= 6) {
  //     return '...${blockHash.substring(blockHash.length - 6)}';
  //   }
  //   return '...$blockHash';
  // }

  /// 获取结果文本（单/双）
  String _getResultText(int? result) {
    if (result == null) return '';
    return (result % 2 == 1) ? LocaleKeys.single.tr : LocaleKeys.double.tr;
  }

// /// 获取结果颜色
// Color _getResultColor(int? result) {
//   if (result == null) return AppColor.textPrimary.withOpacity(0.7);
//   return (result % 2 == 1)
//       ? AppColor.homePrizePoolIndicator
//       : AppColor.gameResultEven;
// }
}
